import axios, {
  AxiosRequestConfig,
  AxiosRequestHeaders,
  AxiosResponse,
  AxiosInstance,
} from 'axios';
import { getToken } from '@/utils/auth';
import { Message } from '@arco-design/web-vue';

import router from '@/router';
const env = import.meta.env.VITE_API_BASE_URL;
const instance: AxiosInstance = axios.create({
  baseURL: env,
  timeout: 10000,
});

interface CustomResponseData {
  code: number;
  msg: string;
  data?: any;
}

// 添加请求拦截器
instance.interceptors.request.use(
  function (config: AxiosRequestConfig) {
    let token = getToken();
    if (token && config) {
      (config.headers as AxiosRequestHeaders).token = token;
    }

    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(function (response: AxiosResponse) {
  let { data } = response;
  if (data.code == 4001) {
    Message.error('登录已经过期请重新登录');
    router.push({ name: 'login' });
  }
  return Promise.resolve(response);
});

export default instance;
